package com.aggregate.pay.lianlianpay.support;

import java.util.Base64;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.lianlianpay.support.utils.JSON;
import com.aggregate.pay.lianlianpay.support.utils.RSA;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 连连付代付接口签名工具类
 * @author Moyq5
 * @date 2019年4月26日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	
	public static boolean verify(String data, String sign, String key) {
		log.debug("连连付->验签：{}", sign);
		log.debug("连连付->验签内容：{}", data);
		try {
			return RSA.verify(data.getBytes("UTF-8"), Base64.getDecoder().decode(sign), Base64.getDecoder().decode(key));
		} catch (Exception e) {
			log.error("连连付->验签异常", e);
		}
		return false;
	}
	
	public static String sign(Object obj, String key) {
		String json = JSON.toString(obj);
		String queryString = toQueryString(json);
		log.debug("连连付->签名内容：{}", queryString);
		String sign = null;
		try {
			sign = Base64.getEncoder().encodeToString(RSA.sign(queryString.getBytes("UTF-8"), Base64.getDecoder().decode(key)));
		} catch (Exception e) {
			log.error("连连付->签名异常", e);
		}
		log.debug("连连付->签名值：{}", sign);
		return sign;
	}
	
	public static String toQueryString(String json) {
		Map<String, Object> map = JSON.toObject(json, new TypeReference<TreeMap<String, Object>>() {});
		map.remove("sign");
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, Object> entry: map.entrySet()) {
			if (null != entry.getValue() && !String.valueOf(entry.getValue()).trim().isEmpty()) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		if (sb.length() > 0) {
			sb.delete(sb.length() - 1, sb.length());
		}
		return sb.toString();
	}
	
}